package com.vn.toaa.tintinscreenoff;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;

import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppAd.AdMode;
import com.vn.tooa.screenoff.R;

interface SettingCommunicator {
	void onReceive();
}

public class SettingActivity extends BaseAdsActivity implements OnClickListener, SettingCommunicator {

	public static final String TAG = SettingActivity.class.getSimpleName();
	private CheckBox mCbEnableVibrator;
	private CheckBox mCbBackToHome;
	private CheckBox mCbEnableSound;
	private CheckBox mCbEnableNotification;
	private Button mBtUninstall;
	private Button mBtMoreApps;
	private Button mBtRateApp;
	private SharedPreferences mSharedPreferences;
	private MyDialogFragment mDialogFragment;
	private boolean mOriginalEnableVibrator;
	private boolean mOriginalBackToHome;
	private boolean mOriginalEnableSound;
	private boolean mOriginalEnableNotification;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		StartAppAd.init(getApplicationContext(), Constant.STARTAPP_DEVELOPER_ID, Constant.STARTAPP_APP_ID);

		setContentView(R.layout.setting_activity);

		mCbEnableVibrator = (CheckBox) findViewById(R.id.checkbox_enable_vibration);
		mCbBackToHome = (CheckBox) findViewById(R.id.checkbox_back_to_home);
		mCbEnableSound = (CheckBox) findViewById(R.id.checkbox_enable_sound);
		mCbEnableNotification = (CheckBox) findViewById(R.id.checkbox_enable_notification);
		mBtUninstall = (Button) findViewById(R.id.button_uninstall);
		mBtMoreApps = (Button) findViewById(R.id.button_get_more_apps);
		mBtRateApp = (Button) findViewById(R.id.button_vote);

		// show ads
		showExitAdWhenBack();
		new Handler().postDelayed(new Runnable() {
			public void run() {
				showInterstitialAd(AdMode.AUTOMATIC);
			}
		}, 1000);

		mBtMoreApps.setOnClickListener(this);
		mBtUninstall.setOnClickListener(this);
		mBtRateApp.setOnClickListener(this);

		mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		mOriginalEnableVibrator = mSharedPreferences.getBoolean(Constant.PREFERS_SETTING_ENABLE_VIBRATOR, false);
		mOriginalBackToHome = mSharedPreferences.getBoolean(Constant.PREFERS_SETTING_BACKTOHOME, false);
		mOriginalEnableSound = mSharedPreferences.getBoolean(Constant.PREFERS_SETTING_ENABLE_SOUND, false);
		mOriginalEnableNotification = mSharedPreferences
				.getBoolean(Constant.PREFERS_SETTING_ENABLE_NOTIFICATION, false);

		mCbEnableVibrator.setChecked(mOriginalEnableVibrator);
		mCbBackToHome.setChecked(mOriginalBackToHome);
		mCbEnableSound.setChecked(mOriginalEnableSound);
		mCbEnableNotification.setChecked(mOriginalEnableNotification);
		mCbEnableNotification.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				try {
					if (isChecked) {
						createNotification();
					} else {
						cancelNotification(0);
					}
				} catch (Exception e) {
				}
			}
		});
		mDialogFragment = new MyDialogFragment();
		mDialogFragment.mCommunicator = this;
	}

	@Override
	public void onBackPressed() {
		if (hasConfigChanged()) {
			mDialogFragment.show(getSupportFragmentManager(), "confirmation");
		} else {
			super.onBackPressed();
		}
	}

	public void createNotification() {
		// Prepare intent which is triggered if the
		// notification is selected
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

		// Build notification
		// Actions are just fake
		Notification noti = new NotificationCompat.Builder(this).setContentTitle(getString(R.string.notification_title))
				.setContentText(getString(R.string.notification_text)).setSmallIcon(R.drawable.ic_launcher)
				.setContentIntent(pIntent).setAutoCancel(false).setOngoing(true).build();

		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.notify(0, noti);
	}

	public void cancelNotification(int notificationId) {
		if (Context.NOTIFICATION_SERVICE != null) {
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
			nMgr.cancel(notificationId);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_get_more_apps:
			try {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				String uriString = String.format("market://search?q=pub:%s", Constant.PUBLISHER_NAME);
				intent.setData(Uri.parse(uriString));
				startActivity(intent);
			} catch (Exception e) {
				LogManager.error(TAG, e.getMessage());
			}
			overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
			break;
		case R.id.button_uninstall:
			ComponentName devAdminReceiver = new ComponentName(this, CustomDeviceAdminReceiver.class);
			DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
			dpm.removeActiveAdmin(devAdminReceiver);
			Toast.makeText(getApplicationContext(), R.string.toast_deactivate_device_admin, Toast.LENGTH_SHORT).show();
			Uri packageURI = Uri.parse("package:" + getPackageName());
			Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
			startActivity(uninstallIntent);
			break;

		case R.id.button_vote:
			try {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				String uriString = String.format("market://details?id=%s", getPackageName());
				intent.setData(Uri.parse(uriString));
				startActivity(intent);
			} catch (Exception e) {
				LogManager.error(TAG, e.getMessage());
			}
			overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
			break;
		default:
			break;
		}
	}

	/**
	 * Checks for config changed.
	 * 
	 * @return true, if successful
	 */
	private boolean hasConfigChanged() {
		if (mOriginalEnableVibrator != mCbEnableVibrator.isChecked()
				|| mOriginalBackToHome != mCbBackToHome.isChecked()
				|| mOriginalEnableSound != mCbEnableSound.isChecked()
				|| mOriginalEnableNotification != mCbEnableNotification.isChecked()) {
			return true;
		}
		return false;
	}

	public static class MyDialogFragment extends DialogFragment {

		public SettingCommunicator mCommunicator;

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			Builder builder = new Builder(getActivity());
			builder.setTitle(R.string.dialog_confirmatoin_title);
			builder.setIcon(android.R.drawable.ic_dialog_alert);
			builder.setMessage(R.string.dialog_confirmation_message);
			builder.setPositiveButton(R.string.dialog_button_ok, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					mCommunicator.onReceive();
				}
			});
			builder.setNegativeButton(R.string.dialog_button_cancel, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			return builder.create();
		}
	}

	@Override
	public void onReceive() {
		Editor editor = mSharedPreferences.edit();
		editor.putBoolean(Constant.PREFERS_SETTING_ENABLE_VIBRATOR, mCbEnableVibrator.isChecked());
		editor.putBoolean(Constant.PREFERS_SETTING_BACKTOHOME, mCbBackToHome.isChecked());
		editor.putBoolean(Constant.PREFERS_SETTING_ENABLE_SOUND, mCbEnableSound.isChecked());
		editor.putBoolean(Constant.PREFERS_SETTING_ENABLE_NOTIFICATION, mCbEnableNotification.isChecked());
		editor.commit();
		runOnUiThread(new Runnable() {
			public void run() {
				finish();
			}
		});
	}
}
